import clonedeep from 'lodash.clonedeep';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { GetWorkPlaceList } from '@/apis/management/organization/organizationManagement';
import { PutOnboardingProcedureDetails } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { GetSectionPersonnel } from '@/apis/management/human/baseSetting/leaveSetting';
import { Message } from '@arco-design/web-vue';
import HumanRosterModal from '@/components/HumanRosterModal/index.vue';
import DepartmentRosterModal from '@/components/DepartmentRosterModal/index.vue';
import { GetHumanRosterList } from '@/apis/management/human/humanRoster';

interface formType {
  id?: number;
  did?: number;
  edit: boolean;
  handlerProcess: string;
  handlerDept: number | null;
  handlerDeptName: string;
  handlerUser: number | null;
  handlerUserName: string;
  handlerAddr: number | null;
  demands: {
    handlerMatters: string;
    matterAsk: string;
  }[];
}

export default defineComponent({
  emits: ['update:visible', 'updateFromData', 'updateFromDataOne'],
  props: ['visible', 'fromData', 'allNode'],

  setup(
    props: { fromData: formType; visible: boolean; allNode: string[] },
    { emit }
  ) {
    const form = ref<formType>({
      edit: false,
      handlerProcess: '',
      handlerDept: null,
      handlerDeptName: '',
      handlerUser: null,
      handlerUserName: '',
      handlerAddr: null,
      demands: [{ handlerMatters: '', matterAsk: '' }]
    });
    watch(
      () => props.fromData,
      () => {
        form.value = clonedeep(props.fromData);
        form.value.handlerUserName = getRoster(
          form.value.handlerUser as number
        );
      }
    );

    const columns = [
      {
        title: '办理事项',
        dataIndex: 'handlerMatters',
        slotName: 'handlerMatters'
      },
      {
        title: '办理事项要求',
        dataIndex: 'matterAsk',
        slotName: 'matterAsk'
      },
      {
        title: '操作',
        slotName: 'operation'
      }
    ];
    const departmentSelectData: any = reactive({ data: [] }); // 部门
    const agentSelectData: any = reactive({
      data: []
    }); // 办理人
    const locationSelectData: any = reactive({ data: [] }); // 地点

    const dealTreeData = (treeData: any) => {
      const data = treeData.map((item) => ({
        ...item,
        // 新增title字段
        title: item.name,
        // 新增叶子节点字段
        disabled: item.node !== '部门' || item.enable !== 1,
        // 如果children为空数组，则置为null
        children:
          item.children && item.children.length
            ? dealTreeData(item.children)
            : null
      }));
      return data;
    };
    const init = async () => {
      const { content } = (await GetWorkPlaceList({
        pageNumber: 0,
        pageSize: -1
      })) as any;
      locationSelectData.data = content;
      const Getlist: any = await GetOrganizationList({});
      console.log('=======================Getlist=============');
      console.log(Getlist);
      console.log('====================================');
      departmentSelectData.data = dealTreeData(Getlist);
      const list = await GetHumanRosterList({
        pageNumber: 0,
        pageSize: -1,
        typeName: '1,2,3,4,5,6,7,8,9,10,11,12'
      });
      agentSelectData.data = list.content;
    };
    const getRoster = (id: number) => {
      let s = '';
      s = agentSelectData.data?.filter((ele: any) => ele.id === id)[0]?.name;
      if (s) return s;
      return void 0;
    };
    init();
    const departmentSelect = ref(false);
    const personSelect = ref(false);
    const spaceSelect = ref(false);
    const handleOk = async () => {
      if (
        props.allNode &&
        props.allNode.length !== 0 &&
        props.allNode.indexOf(form.value.handlerProcess) !== -1 &&
        !props.fromData.id
      ) {
        return Message.error('办理环节名称不能重复');
      }
      console.log('updateFromDataOne', clonedeep(form.value));

      emit('updateFromDataOne', clonedeep(form.value));
      emit('update:visible', false);
      departmentSelect.value = false;
      personSelect.value = false;
      spaceSelect.value = false;
    };
    const handleCancel = () => {
      emit('update:visible', false);
      departmentSelect.value = false;
      personSelect.value = false;
      spaceSelect.value = false;
    };
    const del = (index: number) => {
      form.value.demands?.splice(index, 1);
    };
    const add = () => {
      form.value.demands?.push({ handlerMatters: '', matterAsk: '' });
    };
    const changeGetlistData = (data: any) => {
      let newData: any = [];
      for (const item of data) {
        if (typeof item.ctlValue !== 'object' || !item.ctlValue.length) return;
        for (const items of item.ctlValue) {
          newData.push({ id: items.id, value: items.ctlValue });
        }

        if (item.children && item.children.length !== 0) {
          newData = newData.concat(changeGetlistData(item.children));
        }
      }

      return newData;
    };

    const humanRosterVisible = ref(false); // 是否显示人员花名册弹窗
    const deptRosterVisible = ref(false); // 是否显示部门花名册弹窗
    const currDeptId = ref(0); //  当前部门id
    const deptChange = async (id: number) => {
      // deptRosterVisible.value = true;
      // humanRosterVisible.value = false;
      currDeptId.value = id;
      // const res = await GetSectionPersonnel({ id });
      // agentSelectData.data.length = 0;
      // form.value.handlerUser = null;
      // agentSelectData.data = res ? res : [];
    };

    const selectedHuman = (visible: boolean) => {
      if (visible) {
        console.log('====================================');
        console.log(11);
        console.log('====================================');
        if (form.value.handlerDept) {
          deptRosterVisible.value = true;
          humanRosterVisible.value = false;
          console.log('=================================222===');
          console.log(deptRosterVisible.value);
          console.log('====================================');
        } else {
          console.log('====================================');
          console.log(33);
          console.log('====================================');
          deptRosterVisible.value = false;
          humanRosterVisible.value = true;
        }
      }
    };

    const departmentRosterEmit = (data: any) => {
      form.value.handlerUser = data.id;
      form.value.handlerUserName = data.name;
      console.log(data);
    };

    const humanRosterEmit = (data: number) => {
      form.value.handlerUser = data.id;
      form.value.handlerUserName = data.name;
    };

    return () => (
      <>
        <a-drawer
          width={700}
          visible={props.visible}
          onOk={handleOk}
          onCancel={handleCancel}
          unmountOnClose
          v-slots={{
            title: title(form?.handlerProcess),
            default: () => (
              <>
                <a-form model={form}>
                  <a-form-item label="办理环节：">
                    <a-input
                      v-model={form.value.handlerProcess}
                      placeholder="请输入"
                    />
                  </a-form-item>
                  <a-form-item>
                    <div>
                      <a-table
                        width={600}
                        columns={columns}
                        data={form.value.demands}
                        pagination={false}
                        stripe={true}
                        v-slots={{
                          handlerMatters: (props: any) => (
                            <a-input
                              v-model={
                                form.value.demands[props.rowIndex]
                                  .handlerMatters
                              }
                            />
                          ),
                          matterAsk: (props: any) => (
                            <a-input
                              v-model={
                                form.value.demands[props.rowIndex].matterAsk
                              }
                            />
                          ),
                          operation: (props: any) => (
                            <a-button
                              type="text"
                              status="danger"
                              onClick={() => del(props.rowIndex)}
                            >
                              删除
                            </a-button>
                          )
                        }}
                      ></a-table>
                      {/* <a-button type="text"  onClick={add}>新增 </a-button> */}
                      <a-button type="text" onClick={add}>
                        <icon-plus /> 新增{' '}
                      </a-button>
                    </div>
                  </a-form-item>
                  <a-form-item label="办理部门：">
                    <div style="display:flex;flex-direction: column;width:100%">
                      {/* <a-switch
                      v-model={departmentSelect.value}
                      style="width: fit-content;margin-bottom: 20px;"
                    /> */}
                      {/* <a-select
                      onChange={getID}
                      field-names={{ value: 'id', label: 'value' }}
                      options={departmentSelectData.data}
                      v-model={form.value.handlerDept}
                      placeholder="请选择"
                    /> */}
                      <a-tree-select
                        data={departmentSelectData.data}
                        field-names={{ key: 'id', title: 'name' }}
                        placeholder="请选择"
                        v-model={form.value.handlerDept}
                        onChange={deptChange}
                        allow-clear={true}
                      ></a-tree-select>
                    </div>
                  </a-form-item>
                  <a-form-item label="办理人：">
                    <div style="display:flex;flex-direction: column;width:100%">
                      {/* <a-switch
                      v-model={personSelect.value}
                      style="width: fit-content;margin-bottom: 20px;"
                    /> */}
                      <a-select
                        field-names={{ value: 'userId', label: 'name' }}
                        v-model={form.value.handlerUserName}
                        placeholder="请选择"
                        popup-visible={false}
                        onPopupVisibleChange={selectedHuman}
                        allow-clear={true}
                      />
                    </div>
                  </a-form-item>
                  {/* <a-form-item label="办理人电话：">
                  <a-input disabled placeholder="系统自动读取办理人电话" />
                </a-form-item> */}
                  <a-form-item label="办理地点：">
                    <div style="display:flex;flex-direction: column;width:100%">
                      {/* <a-switch
                      v-model={spaceSelect.value}
                      style="width: fit-content;margin-bottom: 20px;"
                    /> */}
                      <a-select
                        field-names={{ value: 'id', label: 'name' }}
                        options={locationSelectData.data}
                        v-model={form.value.handlerAddr}
                        placeholder="请选择"
                        allow-clear={true}
                      />
                    </div>
                  </a-form-item>
                </a-form>
                <DepartmentRosterModal
                  v-model:visible={deptRosterVisible.value}
                  id={currDeptId.value}
                  onDepartmentRosterEmit={departmentRosterEmit}
                />
                <HumanRosterModal
                  v-model:visible={humanRosterVisible.value}
                  onHumanRosterEmit={humanRosterEmit}
                />
              </>
            )
          }}
        ></a-drawer>
      </>
    );
  }
});

function title(node?: string) {
  const title = (node ? '编辑' : '新增') + '事项';
  return title;
}
